// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';

// css OR less预编译器
import styles from './All.less';

// 图片

const Option = { Select };

/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ report, loading }) => ({
  report,
  loading: loading.models.runpointsRule,
}))
@Form.create()
class Report extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    /* pageValues:{current: 1, pageSize: 10, total: 0}, */
    StocksDetailVisible: false, // modal开关
    OptionVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
    currentDataSource: [], // 表剩余数据
    Beta: '', // 表剩余数据
    BetaDate: '', // 表剩余数据
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      if (record[dataIndex] === '股票合计') {
        return true;
      }
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumns() {
    return [
      {
        title: '股票代码',
        align: 'center',
        width: '50%',
        dataIndex: 'code',
        sorter: (a, b) => {
          const c = [a.code, b.code].sort();
          if (c[0] === a.code) {
            return 1;
          }
          return -1;
        },
        ...this.getColumnSearchProps('stock'),
      },
      {
        title: '财报日期',
        width: '50%',
        dataIndex: 'reportDate',
        align: 'center',
        sorter: (a, b) => DateStamp(a.reportDate) - DateStamp(b.reportDate),
      },
    ];
  }

  handleStandardTableChange = (pagination, filtersArg, sorter, extra) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      currentDataSource: extra.currentDataSource,
      total: extra.currentDataSource.length - 1,
    });
  };

  onSelectType(e) {
    this.setState({
      Beta: e.target.value,
      BetaDate: '',
    });
  }

  searchBeta() {
    const { dispatch } = this.props;
    dispatch({
      type: 'report/GetSearchByCode',
      payload: this.state.Beta,
      callback: res => {
        this.setState({
          BetaDate: res.data,
        });
      },
    });
  }

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const {
      loading,
      report: { stocks },
    } = this.props;
    const {
      listLoading,
      selectedRows,
      record,
      StocksDetailVisible,
      OptionVisible,
      currentDataSource,
      BetaDate,
    } = this.state;
    let columns = [];
    if (columns.length === 0 && stocks.code === 1) {
      columns = this.getColumns();
    }
    return (
      <PageHeaderWrapper title="财报查询">
        <Card>
          <Row>
            <Col md={24} sm={24}>
              输入股票代码：
              <Input style={{ width: 240, margin: 8 }} onChange={this.onSelectType.bind(this)} />
              <Button onClick={this.searchBeta.bind(this)} style={{ margin: 8 }} type="primary">
                搜索
              </Button>
              &nbsp;&nbsp;&nbsp;{BetaDate === null ? '暂无数据' : BetaDate}
            </Col>
          </Row>
          <br />
          {stocks.code === 0 ? (
            <Loading />
          ) : (
            <div>
              <div style={{ margin: 8, fontSize: '1rem' }}>共计：{currentDataSource.length}</div>
              <StandardTable
                selectedRows={selectedRows}
                loading={listLoading}
                data={stocks}
                columns={columns}
                style={{ tableLayout: 'fixed' }}
                className={styles.TableLayout}
                scroll={{ y: 618 }}
                bordered
                onChange={this.handleStandardTableChange}
                pagination={false}
              />
            </div>
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'report/GetCodeList',
      callback: res => {
        this.setState({
          currentDataSource: res.data,
        });
      },
    });
  }

  componentWillUnmount() {}
}

export default Report;
